import { FC, MouseEvent, useEffect, useState } from "react";
import { Upload } from "antd";
import store2 from "store2";
import { DeleteOutlined, PlusOutlined } from "@ant-design/icons";

import styled from "./index.module.css";

interface BaseUploadProps {
  onSuccess: (img: string) => void;
}

const BaseUpload: FC<BaseUploadProps> = ({ onSuccess }) => {
  const [img, setImg] = useState("");

  const onDelete = (e: MouseEvent) => {
    e.stopPropagation(); // 阻止冒泡
    setImg("");
  };

  useEffect(() => {
    onSuccess(img);
  }, [img, onSuccess]);

  const uploadBox = (
    <div className={styled.box}>
      {img ? (
        <div className={styled.img}>
          <img src={img} alt="" />
          <div className={styled.op}>
            <DeleteOutlined onClick={onDelete} />
          </div>
        </div>
      ) : (
        <div className={styled.default}>
          <PlusOutlined style={{ fontSize: 26 }} />
        </div>
      )}
    </div>
  );

  return (
    <Upload
      className={styled.container}
      name="abc"
      action="/api/admin/base/comm/upload"
      headers={{
        // 自定义一些请求头
        Authorization: store2.get("token"),
      }}
      showUploadList={false}
      onChange={({ file }) => {
        if (file.status === "done") {
          // 上传成功，将数据给收集起来
          setImg(file.response.data);
        }
      }}
    >
      {uploadBox}
    </Upload>
  );
};

export default BaseUpload;
